package com.eastcom.mystope.daemon.core.app;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

public class DynamicBeanRegister implements ApplicationContextAware {
	private ApplicationContext context;
	private static Log log = LogFactory.getLog(DynamicBeanRegister.class);
    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }
 
    public void addBeanService(String beanName) {
        if (!context.containsBean(beanName)) {
            Class<?> serviceClass = getServiceClass(beanName);
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass);
            beanDefinitionBuilder.addPropertyValue("servicename", beanName);
            registerBean(beanName, beanDefinitionBuilder.getRawBeanDefinition());
        }
 
    }
 
    /**
     * @desc 向spring容器注册bean
     * @param beanName
     * @param beanDefinition
     */
    private void registerBean(String beanName, BeanDefinition beanDefinition) {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) context;
        BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext
                .getBeanFactory();
        beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);
    }
 
    /**
     * @desc 根据类名查找class
     * @param className
     * @return
     * @throws BVSException
     */
    private Class<?> getServiceClass(String className){
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            log.error("not found service class:" + className, e);
        }
		return null;
    }
}
